import random

from django.shortcuts import render
from django import forms
from django import http
from django.views import View
from django.core import validators
from django.core.validators import RegexValidator
from django_redis import get_redis_connection
from django.conf import settings
from celery_tasks.sms.tasks import send_sms
from .models import UserTest
from web.utils.response_code import RETCODE


# Create your views here.

class RegisterModelForm(forms.ModelForm):
    mobile = forms.CharField(label="手机号", max_length=11,
                             validators=[RegexValidator(r'^1[3-9]\d{9}$', "手机号格式"), ],
                             # widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入手机号"})
                             )
    password = forms.CharField(label="密码", max_length=18,
                               widget=forms.PasswordInput()
                               )
    re_password = forms.CharField(label="重复密码", max_length=18,
                                  widget=forms.PasswordInput())
    verify_sms = forms.CharField(label="验证码", max_length=6)

    class Meta():
        model = UserTest
        fields = ["username", "email", "password", "re_password", "mobile", "verify_sms"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in iter(self.fields):
            self.fields[field].widget.attrs['class'] = 'form-control'
            self.fields[field].widget.attrs['placeholder'] = '请输入' + self.fields[field].label
            self.fields[field].widget.attrs['v-model'] = field
            self.fields[field].widget.attrs['@blur'] = "check_" + field


class RegisterView(View):
    def get(self, request):
        form = RegisterModelForm()
        return render(request, 'app01/register.html', {'form': form})

    def post(self, request):
        # 校验前端发送的数据
        username = request.POST.get("username")
        password = request.POST.get("password")
        email = request.POST.get("email")
        mobile = request.POST.get("mobile")
        code = request.POST.get("verify_sms")
        if not all([username, password, email, mobile, code]):
            return http.JsonResponse({"code": RETCODE.NECESSARYPARAMERR, "err_msg": "缺少必要参数"})
        # 判断验证码是否过期和是否正确
        redis_conn = get_redis_connection("ver_code")
        if redis_conn.get("send_code_%s" % mobile):
            return http.JsonResponse({"coed": RETCODE.NODATAERR, "err_msg": "发送验证码过于频繁"})
        if redis_conn.get("code_%s" % mobile) != code:
            return http.JsonResponse({"code": RETCODE.SMSCODERR, "sms_errmsg": "验证码错误"})

        # 保存数据
        try:
            user = UserTest()
            user.objects.create(
                username=username,
                password=password,
                email=email,
                mobile=mobile,
            )
            user.save()
        except Exception as e:
            return http.JsonResponse({"code": RETCODE.DBERR, "err_msg": "注册失败"})
        # 响应结果
        return http.HttpResponse("注册成功")


class Send_SMS_view(View):
    def get(self, request, mobile):
        # 连接数据库
        try:
            conn_redis = get_redis_connection("ver_code")
        except Exception as e:
            return http.JsonResponse({"code": "100", "errmsg": "数据库连接异常", "err": "e"})
        # 判断是否重复发送验证码

        if conn_redis.get("send_code_%s" % mobile):
            return http.JsonResponse({"code": "100", "verify_sms_error_msg": "已经发送过验证码了"})
        # 把验证码存到redis中
        code = random.randint(100000, 999999)
        # 创建redis管道
        pi = conn_redis.pipeline()
        pi.setex("code_%s" % mobile, 60 * 3, code)
        pi.setex("send_code_%s" % mobile, 60, 1)
        # 执行
        pi.execute()

        # 发送短信验证码
        send_sms.delay(mobile, code)
        print(code)
        # 返回结果
        return http.JsonResponse({"code": "0", "errmsg": "发送短信验证码成功"})


class UploadView(View):
    def get(self, request):
        return render(request, "app01/upload.html")


class CosCredential(View):
    def get(self, request):
        from sts.sts import Sts
        config = {
            # 临时密钥有效时长，单位是秒（30分钟=1800秒）
            'duration_seconds': 1800,
            # 固定密钥 id
            'secret_id': settings.TENCENT_COS_ID,
            # 固定密钥 key
            'secret_key': settings.TENCENT_COS_KEY,
            # 换成你的 bucket
            'bucket': "tartec-1323051912",
            # 换成 bucket 所在地区
            'region': "ap-beijing",
            # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
            # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            'allow_prefix': '*',
            # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            'allow_actions': [
                # 'name/cos:PostObject',
                # 'name/cos:DeleteObject',
                # "name/cos:UploadPart",
                # "name/cos:UploadPartCopy",
                # "name/cos:CompleteMultipartUpload",
                # "name/cos:AbortMultipartUpload",
                "*",
            ],

        }
        sts = Sts(config)
        result_dict = sts.get_credential()
        return http.JsonResponse(result_dict)
